package com.example.s07_restful_swagger.service.impl;

import com.example.s07_restful_swagger.pojo.Message;
import com.example.s07_restful_swagger.service.IMessageService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class MessageServiceImpl implements IMessageService
{
    List<Message> list = new ArrayList<>();

    long count = 0;

    {
        list.add(new Message(1L,"你好","哈哈"));
        count++;
        list.add(new Message(2L,"吃了么?","哈哈"));
        count++;
        list.add(new Message(3L,"拜拜","嘿嘿"));
        count++;

    }

    @Override
    public void save(Message m)
    {
        count++;
        m.setId(count);
        list.add(m);
    }

    @Override
    public boolean removeById(Long id) {

        Iterator<Message> iterator = list.iterator();
        while(iterator.hasNext())
        {
            Message m = iterator.next();
            if(m.getId() == id)
            {
                iterator.remove();;
                return true;
            }
        }
        return false;
    }

    @Override
    public void updateById(Message m) {

        Iterator<Message> iterator = list.iterator();
        while(iterator.hasNext())
        {
            Message tmp = iterator.next();
            if(m.getId() == m.getId())
            {
                tmp.setText(m.getText());
                tmp.setSummary(m.getSummary());
                break;
            }
        }
    }

    @Override
    public Message findById(Long id)
    {
        Iterator<Message> iterator = list.iterator();
        while(iterator.hasNext())
        {
            Message m = iterator.next();
            if(m.getId() == id)
            {
                return m;
            }
        }
        return null;
    }

    @Override
    public List<Message> findAll()
    {
        return list;
    }
}
